<template>
  <div class="attachment-container">
    <!--  TODO:时间轴组件出现多次包含多种情况，后续统一封装  -->
    <div class="time-line">
      <el-timeline :reverse="true">
        <template v-for="item in attachmentListData" :key="item.profileCategoryId">
          <el-timeline-item>
            <div class="attachment-type">
              {{ item.profileCategoryName }}
            </div>
          </el-timeline-item>
          <template v-if="item.crmProfiles">
            <el-timeline-item color="#E1E6ED" size="normal" v-for="field in item.crmProfiles" :key="field.fieldId">
              <div class="attachment-field">
                <div class="attachment-field-name">
                  <div class="name-icon"></div>
                  <div class="name-label">{{ field.title }}</div>
                </div>
                <div class="attachment-field-content">
                  <template v-if="!['FileUpload', 'ImageUpload', 'VideoUpload'].includes(field.fieldName)">
                    <div class="content-file" style="color: #3d3d3d">
                      <span v-if="field.fieldName === 'MultipleSelect'">{{ multipleSelectLable(field).value }}</span>
                      <span v-else-if="field.fieldName === 'CascaderInput'">{{ cascaderInputLable(field).value }}</span>
                      <span v-else-if="field.fieldName === 'UserPicker'">{{ UserPickerLable(field).value }}</span>
                      <span v-else-if="field.fieldName === 'HyperlinkInput'" class="hyper-link">
                        <a :href="field.value" target="_blank">{{ field.value }}</a>
                      </span>
                      <span v-else>{{ field.value }}</span>
                    </div>
                  </template>
                  <template v-if="field.fieldName === 'FileUpload'">
                    <div class="file-item" v-for="fileItem in fileDatas(field).value" :key="fileItem.fileId">
                      <div class="content-file" @click="handelPreview(fileItem)">{{ fileItem.fileName }}</div>
                      <el-button type="primary" round @click="handleDownload(fileItem)">下载</el-button>
                    </div>
                  </template>
                  <image-video-upload
                    v-if="field.fieldName === 'VideoUpload'"
                    :file-list="fileDatas(field).value"
                    fileType="video"
                    disabled
                  />
                  <image-video-upload v-if="field.fieldName === 'ImageUpload'" :file-list="fileDatas(field).value" disabled />
                </div>
              </div>
            </el-timeline-item>
          </template>
          <el-timeline-item v-else color="#E1E6ED" size="normal">
            <div class="attachment-field-empty">
              <div class="field-empty-icon">
                <svg-icon iconClass="annex-empty" className="annex-empty" />
                <div class="field-empty-label">
                  <span>待上传</span>
                  <span>目前版本只支持通过“任务”添加</span>
                </div>
              </div>
            </div>
          </el-timeline-item>
        </template>
      </el-timeline>
    </div>

    <!--   文件预览 start -->
    <r-preview v-if="isShowFilePreview" :src="previewUrl"></r-preview>
    <!--  文件预览 end  -->
  </div>
</template>

<script setup>
import { ref } from "vue";
import useComputedParams from "@/hooks/useComputedParams";
import { attachmentList } from "@/apis/Attachment";
import areaData from "@/assets/pca-code";
import { getAreaLabelsByCode } from "@/utils/address";
import { getFileSuffix } from "@/utils";
import "ranui";
import axios from "axios";

const props = defineProps({
  customerId: {
    type: String,
    default: ""
  }
});

const attachmentListData = ref([]);

const fileDatas = useComputedParams(data => {
  return data.value ? JSON.parse(data.value) : [];
});
const multipleSelectLable = useComputedParams(data => {
  const value = data.value ? JSON.parse(data.value) : [];
  return value.reduce((pre, cur) => {
    return `${pre}${pre ? "," : ""}${cur}`;
  }, "");
});

const cascaderInputLable = useComputedParams(data => {
  const value = data.value ? JSON.parse(data.value) : [];
  const label = getAreaLabelsByCode(areaData, value, "id", "name");
  return label.reduce((pre, cur) => {
    return `${pre}${pre ? "/" : ""}${cur}`;
  }, "");
});

const UserPickerLable = useComputedParams(data => {
  const value = data.value ? JSON.parse(data.value) : [];
  return value.reduce((pre, cur) => {
    return `${pre}${pre ? "," : ""}${cur.name}`;
  }, "");
});

const getAttachmentList = async () => {
  const { data } = await attachmentList(props.customerId);
  attachmentListData.value = data ?? [];
};

/**
 * 附件预览 ppt/excel/word/pdf
 * @param fileItem
 */
const isShowFilePreview = ref(false);
const previewFileType = ["ppt", "pptx", "xlsx", "xls", "doc", "docx", "pdf"];
const previewUrl = ref("");
const handleDownload = fileItem => {
  window.open(fileItem.fileUrl);
};
const handelPreview = fileItem => {
  const isHas = previewFileType.includes(getFileSuffix(fileItem.fileName));
  if (isHas) {
    isShowFilePreview.value = true;
    let type = "";
    const down = (fileUrl, res) => {
      if (fileUrl.toLowerCase().indexOf(".xlsx") > -1) {
        type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
      } else if (fileUrl.toLowerCase().indexOf(".docx") > -1) {
        type = "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
      } else if (fileUrl.toLowerCase().indexOf(".pdf") > -1) {
        type = "application/pdf";
        let blob = new Blob([res], {
          type: "application/pdf"
        });
        const url = window.URL.createObjectURL(blob);
        window.open(url);
        return;
      } else if (fileUrl.toLowerCase().indexOf(".pptx") > -1) {
        type = "application/vnd.openxmlformats-officedocument.presentationml.presentation";
      }
      if (type) {
        let blob = new Blob([res], {
          type: type
        });
        previewUrl.value = window.URL.createObjectURL(blob);
      } else {
        this.$modal.msgError("预览只支持docx,pptx,pdf,xlsx");
      }
    };
    axios
      .request({
        method: "GET",
        url: fileItem.fileUrl,
        responseType: "blob"
      })
      .then(res => {
        down(fileItem.fileUrl, res.data);
      })
      .catch(error => {});
    return;
  }
  window.open(fileItem.fileUrl);
};

getAttachmentList();
</script>

<style scoped lang="scss">
@import "attachment";

.hyper-link {
  a {
    font-size: 14px;
    color: #007dff;
    line-height: 24px;
    text-decoration: underline;
    cursor: pointer;
  }
}
</style>
<style lang="scss">
.r-preview-mask .r-preview-loading {
  display: none !important;
}
</style>
